import React, { Component } from 'react'
import { connect } from 'react-redux'
import UpdateTeamMember from 'graphql/user/team/updateTeamMember.graphql'
import QueryTeamMember from 'graphql/user/team/queryOneTeamMember.graphql'
import deleteDataset from 'graphql/dataset/deleteDataset.graphql'
import { ValidType } from 'components/validForm'
import {
  Form as FormTable,
  Section as TableSection,
  Input,
  Submit,
} from 'components/tableForm'
import { global as globalDuck } from 'ducks'
import { push, replace } from 'connected-react-router'

const getVariables = values => ({
  name: values.name.value,
})

class EditTeam extends Component {
  componentDidMount = () => {
  }

  render() {
    const {
      user, activeDatasetId, link, reLink, activeDataset, org, match
    } = this.props
    const orgName = org.owner_object.name
    let { path } = match.params
    path = path || ''
    const pathArr = path.split('/')
    const teamName = pathArr[pathArr.length - 1]
    const teamPath = path.substr(0, path.length - teamName.length - 1)
    const teamUrl = teamPath !== '' ? `/org/${orgName}/user/teams/list/${teamPath}` : `/org/${orgName}/user/teams/list`
    const mailRule = [
      {
        type: ValidType.REGULAR,
        value: /^[\s\S]*.*[^\s][\s\S]*$/,
        errorMessage: '子组织名称不能为空',
      },
      {
        type: ValidType.REGULAR,
        value: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
        errorMessage: '子组织名称由中文、英文数字包括下划线',
      },
      {
        type: ValidType.REMOTE,
        value: {
          query: QueryTeamMember,
          params: { org: orgName, path: teamPath },
        },
        errorMessage: '该名称已经存',
        getResult: re => re.team_member.length === 0,
      },
    ]
    const deleteRule = [
      {
        type: ValidType.EQ,
        value: teamName,
        errorMessage: `应输入: ${teamName}`,
      },
    ]
    return (
      <FormTable
        initQuery={{
          query: QueryTeamMember,
          variables: { org: orgName, path: teamPath, value: teamName },
          tableName: 'team_member',
        }}
      >
        <TableSection header="编辑子组织">
          <Input
            name="name"
            header="子组织名称"
            description="子组织名称由 1 ~ 63 个字符组成 ，可包含字母、数字。"
            rules={mailRule}
          />
        </TableSection>
        <Submit
          submit={{
            text: '保存',
            variables: { org: orgName, path: teamPath, value: teamName },
            getVariables,
            mutation: UpdateTeamMember,
            success: (data) => {
              link('/empty')
              setTimeout(() => {
                if (data && data.update_team_member && data.update_team_member.returning) {
                  reLink(teamUrl)
                }
              })
            },
          }}
          cancle={{ text: '取消', url: teamUrl }}
          validFields={['name']}
          redirect
        />
        <TableSection header="危险操作区" red>
          <Input
            name="deleteName"
            header="删除当前子组织"
            description={`为了安全起见请您输入当前要删除的子组织名称：${teamName}`}
            rules={deleteRule}
            red
          />
        </TableSection>
        <Submit
          submit={{
            text: '删除',
            variables: { org: orgName, path: teamPath, value: teamName },
            getVariables: () => {},
            mutation: deleteDataset,
            success: () => {
              link('/empty')
              setTimeout(() => {
                reLink(`/org/${orgName}/dataset`)
              })
            },
          }}
          validFields={['deleteName']}
          red
        />
      </FormTable>
    )
  }
}

const mapStateToProps = state => ({
  user: globalDuck.selectors.user(state),
})

const mapDispatchToProps = {
  link: push,
  reLink: replace,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(EditTeam)
